<?php
/**
* AAuth class file.
*
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php MIT Licence
*/

/*
* AAuth class, this class is designed to be extended and implement all abstract
* methods.
* This class defines a simple Role-Based Access Control system for your site.
* Please see the documentation for more information.
*/
abstract class AAuth {

	protected $tasks;

	/**
	* Each task has this format:
	* 	task_name => role1, role2
	* @param Array $task
	*/
	public function add_task($tasks = array()) {
		foreach($tasks as $name => $roles) {
			$this->tasks[$name] = explode(',', str_replace(' ', '', $roles));
		}
	}

	private function get_task_roles($task_name) {
		if(!array_key_exists($task_name, $this->tasks)) {
			return array();
		}
				
		return $this->tasks[$task_name];
	}

	/**
	* This method will be implemented in your own code.
	* It must return the role of your current user, for example:
	* Anonymous, Registered, Administrator or any identificator.
	* Roles must contain no spaces.
	*/
	protected abstract function get_role();

	/**
	* This is a boolean method, you can call it every time you needed
	* to check if the user has permissions for the requested action.
	* @param String $task_name
	* @return boolean Whether or not the current user has permission for the given task
	*/
	public function has_permission($task_name) {
		if($this->get_task_roles($task_name) == '*') {
			return TRUE;
		}
		
		return in_array($this->get_role(), $this->get_task_roles($task_name));
	}

	/**
	* Get either a Gravatar URL or complete image tag for a specified email address.
	* @param string $email The email address
	* @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
	* @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
	* @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
	* @param boole $img True to return a complete IMG tag False for just the URL
	* @param array $atts Optional, additional key/value attributes to include in the IMG tag
	* @return String containing either just a URL or a complete image tag
	* @source http://gravatar.com/site/implement/images/php/
	*/
	function get_gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array()) {
		$url = 'http://www.gravatar.com/avatar/';
		$url .= md5(strtolower(trim($email)));
		$url .= "?s=$s&d=$d&r=$r";
		if ($img) {
			$url = '<img src="' . $url . '"';
			foreach($atts as $key => $val)
				$url .= ' ' . $key . '="' . $val . '"';
			$url .= ' />';
		}
		return $url;
	}

}

// End of ./akaikiwi/libs/AAuth.php
